package org.cogaen.java2d;

import java.awt.Image;

import org.cogaen.core.Core;
import org.cogaen.resource.ResourceHandle;
import org.cogaen.resource.ResourceManager;

public class AnimationHandle extends ResourceHandle {

	private String imageName;
	private AnimationVisual animation;
	private double width;
	private double height;
	private int columns;
	private int rows;
	private double displayTime;
	private int firstFrame;
	private int nFrames;
	
	public AnimationHandle(String name, String imageName, int columns, int rows, double width, double height) {
		super(name);
		this.imageName = imageName;
		this.width = width;
		this.height = height;
		this.columns = columns;
		this.rows = rows;
	}

	public AnimationHandle(String name, String imageName, int columns, int rows) {
		this(name, imageName, columns, rows, 0, 0);
	}
	
	@Override
	public boolean isLoaded() {
		return this.animation != null;
	}

	@Override
	public void load(Core core) {
		Image image = (Image) ResourceManager.getInstance(core).getResource(this.imageName);
		double width = this.width;
		double height = this.height;
		if (width <= 0) {
			width = image.getWidth(null) / this.columns;
		}
		if (height <= 0) {
			height = image.getHeight(null) / this.rows;
		}
		
		this.animation = new AnimationVisual(core, image, this.columns, this.rows, width, height);
		this.animation.setDisplayTime(this.displayTime);
		this.animation.setSequence(this.firstFrame, this.nFrames);
	}

	@Override
	public void unload() {
		this.animation = null;
	}

	@Override
	public Object getResource() {
		// Animations cannot share the same instance, because each instance
		// might render the animation at different positions.
		return this.animation != null ? new AnimationVisual(this.animation) : null;
	}

	public void setDisplayTime(double displayTime) {
		this.displayTime = displayTime;
	}

	public void setFirstFrame(int firstFrame) {
		this.firstFrame = firstFrame;
	}

	public void setNumFrames(int nFrames) {
		this.nFrames = nFrames;
	}
}